package com.gljx.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gljx.web.Entity.Car;
import com.gljx.web.Entity.Department;
import com.gljx.web.Entity.InsuranceReg;
import com.gljx.web.Entity.InsuranceRegEntry;
import com.gljx.web.Entity.PageBean;
import com.gljx.web.Entity.User;
import com.gljx.web.service.CarService;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.InsuranceRegService;

@Controller
@RequestMapping("/")
public class InsuranceRegController {

	//自动注入
	@Autowired
	private InsuranceRegService insuranceRegService;
	
	//自动注入
	@Autowired
	private DepartmentService departmentService;

	//自动注入
	@Autowired
	private CustomLogService customLogService;
	
	//自动注入
	@Autowired
	private CarService carService;
		
	/**
	 * 查询保险登记
	 * @param request
	 * @return
	 */
	@RequestMapping("/queryInsuranceReg/look.action")
    public String queryInsuranceReg(HttpServletRequest request, String flag) {
        PageBean<InsuranceReg> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//时间格式化
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//获取当前时间
		String endTime = sdf.format(new Date());
		//获取前三天
		String beginTime = TimeFormat.getThreeDay();
		try {
			//获取分页
			pb = getPageBean(request,user.getFcompanyid(),beginTime,endTime);
			//获取分页数据
			List<InsuranceReg> insuranceRegs = pb.getBeanList();
			for (InsuranceReg insuranceReg : insuranceRegs) {
				//查询子类信息
				List<InsuranceRegEntry> insuranceRegEntrys = insuranceRegService.selectInsuranceRegEntry(insuranceReg.getFid(), "", "");
				//放入集合
				insuranceReg.setInsuranceRegEntrys(insuranceRegEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("insuranceRegs", insuranceRegs);
			request.setAttribute("pb", pb);
            request.setAttribute("flag", flag);
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/carManagement/insuranceReg/insuranceRegList";
	}
	
	/**
	 * 根据条件查询保险登记
	 * @param request
	 * @param carName 车辆
	 * @param carNumber 车牌号码
	 * @param beginTime 业务开始日期
	 * @param endTime 业务结束日期
	 * @return
	 */
	@RequestMapping("/queryInsuranceRegByInfo")
	public String queryInsuranceRegByInfo(HttpServletRequest request,String carName,String carNumber,String beginTime,String endTime){
		PageBean<InsuranceReg> pb = new PageBean<>();
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		try {
			//去除空格
            carName = carName.trim();
            carNumber = carNumber.trim();
			//获取分页
			pb = getPageBean2(request,user.getFcompanyid(),carName,carNumber,beginTime,endTime);
			//获取分页数据
			List<InsuranceReg> insuranceRegs = pb.getBeanList();
			for (InsuranceReg insuranceReg : insuranceRegs) {
				//查询子类信息
				List<InsuranceRegEntry> insuranceRegEntrys = insuranceRegService.selectInsuranceRegEntry(insuranceReg.getFid(), carName, carNumber);
				//放入集合
				insuranceReg.setInsuranceRegEntrys(insuranceRegEntrys);
			}
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("insuranceRegs", insuranceRegs);
			request.setAttribute("pb", pb);
			request.setAttribute("carName", carName);
			request.setAttribute("carNumber", carNumber);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/backHome/carManagement/insuranceReg/insuranceRegList";
	}
	
	/**
	 * 跳转到添加页面
	 * @param request
	 * @param type
	 * @return
	 */
	@RequestMapping("/insertInsuranceReg")
	public String insertInsuranceReg(HttpServletRequest request,String type){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取部门
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取最大编码
        /*String fnumber = customLogService.selectFunmber("ct_ds_insurancereg",user.getFcompanyid());*/
		//获取下一个编码
        String number = GetFnumber.fnumbers("BX");
		//获取车辆
        List<Car> cars = carService.queryCar(user.getFcompanyid());
        //获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//业务时间
		String time = sdf.format(new Date());
		//把数据传到页面
		request.setAttribute("time", time);
		request.setAttribute("cars", cars);
		request.setAttribute("type", type);
		request.setAttribute("name", user.getName());
		request.setAttribute("department", department);
		request.setAttribute("fnumber", number);
		return "/backHome/carManagement/insuranceReg/editInsuranceReg";
	}
	
	/**
	 * 根据条件查询车辆
	 * @param name
	 * @param fnumber
	 * @return
	 */
	@RequestMapping("/queryCarByInfo")
	@ResponseBody
    public List<Car> queryCarByInfo(String name, String fnumber, HttpServletRequest request) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        List<Car> cars = new ArrayList<>();
		if("".equals(fnumber) && "".equals(name)){
            cars = carService.queryCar(user.getFcompanyid());
        }else{
			cars = carService.queryCarByInfo(name, fnumber);
		}
		return cars;
	}
	
	/**
	 * 添加或修改
	 * @param request
	 * @param insuranceReg
	 * @param fid
	 * @return
	 */
	@RequestMapping("/editInsuranceReg")
	public String editInsuranceReg(HttpServletRequest request,InsuranceReg insuranceReg,String fid){
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//控制单元id
		insuranceReg.setFcontrolunitid(user.getFcompanyid());
		//公司id
		insuranceReg.setCfficompanyid(user.getFcompanyid());
		//获取当前时间
		String time = TimeFormat.timeFormat(new Date());
		//操作人id
		insuranceReg.setFhandlerid(user.getFid());
		/**获取子类信息集合**/
		//序列
		String[] fseq = request.getParameterValues("fseq");
		//车辆
		//String[] carName = request.getParameterValues("carName");
		//车牌号码
		String[] cfcarnumber = request.getParameterValues("cfcarnumber");
		//车辆id
		String[] cfcarid = request.getParameterValues("cfcarid");
		//车类型
		String[] cftype = request.getParameterValues("cftype");
		//办理日期
		String[] cfbizdate = request.getParameterValues("cfbizdate");
		//到期日期
		String[] cfenddate = request.getParameterValues("cfenddate");
		//金额
		String[] cfamount = request.getParameterValues("cfamount");
		//备注
		String[] cfremark = request.getParameterValues("cfremark");
		//添加或修改
		insuranceRegService.editInsuranceReg(insuranceReg,fseq,cfcarnumber,cfcarid,cftype,cfbizdate,cfenddate,cfamount,cfremark,user,time);
		if("".equals(fid) || fid == null){
			//添加日志
			customLogService.addLog("车辆管理", time+"对保险登记进行添加操作", null, user.getFid());
			//重定向到添加页面
			return "redirect:/DrivingSys/insertInsuranceReg?type=3";
		}else{
			//添加日志
			customLogService.addLog("车辆管理", time+"对保险登记进行进行修改操作", null, user.getFid());
			//重定向到查询页面
            return "redirect:/DrivingSys/queryInsuranceReg/look.action?flag=2";
        }
	}
	
	/**
     * 根据fid查询
     * @param request
	 * @param fid
	 * @return
	 */
	@RequestMapping("/queryInsuranceRegByFid")
	public String queryInsuranceRegByFid(HttpServletRequest request,String fid){
		//查询父类信息
		InsuranceReg insuranceReg = insuranceRegService.queryInsuranceRegByFid(fid);
		//查询子类信息
		List<InsuranceRegEntry> insuranceRegEntrys = insuranceRegService.selectInsuranceRegEntry(fid, "", "");
		//获取车辆
        List<Car> cars = carService.queryCar(insuranceReg.getCfficompanyid());
        //查询是否是经办人
        Axamine axamine = new Axamine();
        boolean state = axamine.selectAuditPerson(insuranceReg.getFnumber());
        //把数据传到页面
        request.setAttribute("AuditState", state);
        request.setAttribute("cars", cars);
        request.setAttribute("key", ActivitiKey.PUBLIC_KEY);
        request.setAttribute("insuranceReg", insuranceReg);
		request.setAttribute("insuranceRegEntrys", insuranceRegEntrys);
		return "/backHome/carManagement/insuranceReg/editInsuranceReg";
	}
	
	
	/**
	 * 根据fid删除
	 * @param request
	 * @param fid 单个
	 * @param deleteId 多个
	 * @return
	 */
	@RequestMapping("/deleteInsuranceRebByFid")
    public String deleteInsuranceRebByFid(HttpServletRequest request, String fid, String[] deleteId, String[] fnumber, String fnumber2) {
        //获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//删除
        insuranceRegService.deleteInsuranceRebByFid(fid, deleteId, fnumber, fnumber2);
        //添加日志
		customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date())+"对保险登记进行进行删除操作", null, user.getFid());
		//重定向到查询页面
		return "redirect:/DrivingSys/queryInsuranceReg/look.action";
	}
	
	/**
	 * 审核，反审核
	 * @param request
	 * @param type 1：审核，2：反审核
	 * @param fid
	 * @return
	 */
	@RequestMapping("/auditInsuranceReg")
	@ResponseBody
    public int auditInsuranceReg(HttpServletRequest request, String type, String fid, String message, String state, String fnumber) {
        //获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//查询子类信息
		List<InsuranceRegEntry> insuranceRegEntrys = insuranceRegService.selectInsuranceRegEntry(fid, "", "");
		//审核，反审核
        int i = insuranceRegService.auditInsuranceReg(fid, type, user.getFid(), insuranceRegEntrys, message, state, fnumber);
		//添加日志
		customLogService.addLog("车辆管理", "对保险登记进行进行审核操作单据编号 " + fnumber, null, user.getFid());
		return i;
	}

    /**
     * 提交
     *
     * @param fid
     * @return
     */
    @RequestMapping("/submitInsuranceReg")
    @ResponseBody
    public int submitInsuranceReg(String fid, HttpServletRequest request, String fnumber, String auditState) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        InsuranceReg insuranceReg = new InsuranceReg();
        insuranceReg.setFid(fid);
        insuranceReg.setFlastupdateuserid(user.getFid());
        insuranceReg.setCfbillstate(4L);
        //创建流程
        Axamine axamine = new Axamine();
        axamine.submissionProcess(fnumber);
        int i = insuranceRegService.modifyInsuranceReg(insuranceReg);
		//添加日志
		customLogService.addLog("车辆管理", "对保险登记进行进行提交操作单据编号 " + fnumber, null, user.getFid());
		return i;
    }

    @SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<InsuranceReg> getPageBean2(HttpServletRequest request,String companyId,String carName,String carNumber,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select distinct t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,");
		psql.append("t.cfbillstate from  ct_ds_insurancereg t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid ");
		psql.append("left join  ct_ds_insuranceregentry i on i.fparentid = t.fid left join ct_ds_car c on  i.cfcarid = c.fid  where t.fcontrolunitid = '"+companyId+"'");
		if("".equals(carName)){
			
		}else{
			psql.append(" and c.fname_l2 like '%"+carName+"%'");
		}
		if("".equals(carNumber)){
			
		}else{
			psql.append(" and i.cfcarnumber like '%"+carNumber+"%'");
		}
		if("".equals(beginTime) || "".equals(endTime)){

		}else{
			psql.append("  and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
		}
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 50; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= insuranceRegService.selectPage(pindex, psql.toString(), psize);
		PageBean<InsuranceReg> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<InsuranceReg>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}
	
	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类 
	 * @throws Exception
	 */
	public PageBean<InsuranceReg> getPageBean(HttpServletRequest request,String companyId,String beginTime,String endTime) throws Exception
	{

		int offset;//从第几条数据开始加载
		if(request.getParameter("pager.offset")==null){  
			offset=0;  
		}else{  
			offset=Integer.parseInt(request.getParameter("pager.offset"));  
		}	
		//拼接SQL语句
		StringBuffer psql = new  StringBuffer();
		psql.append("select t.fid,t.fnumber,t.fdescription,to_char(t.fbizdate,'yyyy-MM-dd')fbizdate,u.name createName,us.name auditName,t.cfbillstate from ");
		psql.append(" ct_ds_insurancereg t left join t_e_user u  on t.fcreatorid=u.fid left join t_e_user us on t.fauditorid = us.fid where t.fcontrolunitid = '"+companyId+"'");
		psql.append(" and t.fbizdate between to_date('"+beginTime+"','YYYY/MM/DD') and to_date('"+endTime+"','YYYY/MM/DD')");
        psql.append(" order by to_char(t.fbizdate,'yyyy-MM-dd') desc");
        int psize = 10; //每页显示数
        int pindex=offset/psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap= insuranceRegService.selectPage(pindex, psql.toString(), psize);
		PageBean<InsuranceReg> pb=new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount=getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int)paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<InsuranceReg>)paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception
	{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=insuranceRegService.selectPageCount(psql);
		return paramMap;		
	}

    /**
     * 导出Excel
     *
     * @param request
     * @param response
     * @param carName
     * @param carNumber
     * @param beginTime
     * @param endTime
     */
    @RequestMapping("/importInsuranceReg")
    public void importInsuranceReg(HttpServletRequest request, HttpServletResponse response, String carName,
                                   String carNumber, String beginTime, String endTime) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //定义接收类型
        List<Object> data = new ArrayList<>();
        //查询数据
        List<InsuranceRegEntry> insuranceRegs = insuranceRegService.selectInsuranceRegByInfo(user.getFcompanyid(), carName.trim(), carNumber.trim(), beginTime, endTime);
        for (InsuranceRegEntry insuranceRegEntry : insuranceRegs) {
            data.add(insuranceRegEntry.getFnumber());
            data.add(insuranceRegEntry.getFbizdate2());
            data.add(insuranceRegEntry.getFdescription());
            data.add(insuranceRegEntry.getShName());
            data.add(insuranceRegEntry.getZdrName());
            data.add(stateToString.billsState(insuranceRegEntry.getCfbillstate()));
            data.add(stateToString.carType(insuranceRegEntry.getCftype()));
            data.add(insuranceRegEntry.getCfbizdate());
            data.add(insuranceRegEntry.getCfenddate());
            data.add(insuranceRegEntry.getCfremark());
            data.add(insuranceRegEntry.getCarName());
            data.add(insuranceRegEntry.getCfcarnumber());
            data.add(insuranceRegEntry.getCfamount());
        }
        //头部数据
        String head[] = {"单据编号", "业务日期", "参考信息", "审核人名称", "制单人名称", "单据状态", "类型", "办理日期", "到期日期", "备注", "车辆", "车牌", "金额"};
        //长度
        Integer length[] = {9000, 4000, 5000, 3000, 3000, 2600, 4000, 4000, 4000, 6500, 5000, 2600, 2600};
        try {
            //导出Excel
            CommonExport.importExcel(response, "保险登记" + TimeFormat.getNowTime2() + ".xls", "保险登记", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
